using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;

namespace MefContainer
{
	public static class MefHelper
	{
		private static CompositionContainer _container;

		private static List<Assembly> _assemblies;

		private static List<string> _exceptString;

		public static List<Assembly> Assemblies => _assemblies;

		public static void Init(List<string> exceptString = null)
		{
			_assemblies = new List<Assembly>();
			_exceptString = (exceptString ?? new List<string>());
			LoadAssembly();
			AggregateCatalog catalog = new AggregateCatalog();
			_assemblies.ForEach(delegate(Assembly x)
			{
				catalog.Catalogs.Add(new AssemblyCatalog(x));
			});
			_container = new CompositionContainer(catalog);
		}

		public static T GetExportedValue<T>()
		{
			return _container.GetExportedValue<T>();
		}

		public static T GetExportedValue<T>(string contract)
		{
			return _container.GetExportedValue<T>(contract);
		}

		public static T GetExportedValue<T>(Type service)
		{
			return _container.GetExportedValue<T>(AttributedModelServices.GetContractName(service));
		}

		public static T GetExportedValue<T>(Type service, string key)
		{
			string contractName = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(service) : key;
			return _container.GetExportedValue<T>(contractName);
		}

		public static IEnumerable<T> GetExportedValues<T>()
		{
			return _container.GetExportedValues<T>();
		}

		public static IEnumerable<T> GetExportedValues<T>(string contract)
		{
			return _container.GetExportedValues<T>(contract);
		}

		public static IEnumerable<T> GetExportedValues<T>(Type service, string key)
		{
			string contractName = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(service) : key;
			return _container.GetExportedValues<T>(contractName);
		}

		public static void SatisfyImportsOnce(object instance)
		{
			_container.SatisfyImportsOnce(instance);
		}

		public static void Compose(CompositionBatch batch)
		{
			_container.Compose(batch);
		}

		private static void LoadAssembly()
		{
			string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
			DirectoryInfo directoryInfo = new DirectoryInfo(baseDirectory);
			List<FileInfo> exeFiles = directoryInfo.GetFiles("*.exe", SearchOption.AllDirectories).ToList();
			List<FileInfo> collection = directoryInfo.GetFiles("*.dll", SearchOption.AllDirectories).ToList();
			exeFiles.AddRange(collection);
			if (_exceptString.Any())
			{
				_exceptString.ForEach(delegate(string exceptStr)
				{
					(from x in exeFiles
					where x.Name.StartsWith(exceptStr)
					select x).ToList().ForEach(delegate(FileInfo x)
					{
						exeFiles.Remove(x);
					});
				});
			}
			foreach (FileInfo item2 in exeFiles)
			{
				Assembly item = Assembly.LoadFile(item2.FullName);
				_assemblies.Add(item);
			}
		}
	}
}
